package com.ztom.top100;

import java.util.Deque;
import java.util.LinkedList;

/**
 * 验证二叉搜索树
 * <p>
 * https://leetcode-cn.com/problems/validate-binary-search-tree/
 *
 * @author ZhangTao
 */
public class Code39IsValidBST {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 递归
     *
     * @param root
     * @return
     */
    private long pre = Long.MIN_VALUE;
    public boolean isValidBST1(TreeNode root) {
        if (root == null) {
            return true;
        }

        return in(root);
    }

    private boolean in(TreeNode node) {
        if (node == null) {
            return true;
        }
        if (!in(node.left)) {
            return false;
        }
        if (node.val <= pre) {
            return false;
        }
        // 记录前一个节点的值
        pre = node.val;
        return in(node.right);
    }

    /**
     * 迭代
     *
     * @param root
     * @return
     */
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }

        // 记录前一个节点的值
        long pre = Long.MIN_VALUE;

        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            if (node != null) {
                stack.addLast(node);
                node = node.left;
            } else {
                node = stack.pollLast();
                if (node.val <= pre) {
                    return false;
                }
                pre = node.val;

                // 去右树
                node = node.right;
            }
        }
        return true;
    }
}
